package cn.edu.sdjzu.xg.eagle.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tg.si@188.com
 * @todo
 * @since 2024/4/16 10:31
 */
@WebFilter(filterName = "encoding1", urlPatterns = {"/*"})
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑（可选）
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 1. 设置请求编码（必须在读取参数/输入流之前）
        request.setCharacterEncoding("UTF-8");

        // 2. 强制设置响应编码（覆盖后续可能的错误设置）
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");

        // 3. 传递请求和响应给后续过滤器或Servlet
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理逻辑（可选）
    }
}